package bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * description:
 * author:zt
 * date:2021-09-09
 */
public class BIOServer {
    public static void main(String[] args) throws Exception{
        ExecutorService threadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动");

        while (true){
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");

            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handler(socket);
                }
            });
        }
    }

    //和客户端通讯的方法
    public static void handler(Socket socket) {
        try {
            System.out.println("当前线程id："+Thread.currentThread().getId()+"，名字："+Thread.currentThread().getName());
            byte[] bytes = new byte[1024];

            InputStream inputStream = socket.getInputStream();
            while (true){
                int len = inputStream.read(bytes);
                if (len!=-1) System.out.println(new String(bytes,0,len));
                else break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭与客户端的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
